import React from 'react';
import {Bar, Line, Pie, Rose} from '@ant-design/plots';
import {Col, Row} from 'antd';

class Demo3 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      plotData: [],
      pieData: [],
      lineData: [],
      roseData: [],
      isLoading: false
    };
  }

  componentDidMount() {
    this.getAppInfo();
  }

  getAppInfo = () => {
    const url = "http://1.94.134.166:8805/appUseInfo/state?beginDate=2024-01-01&endDate=2024-11-01&stateType=ByMonth";
    fetch(url, {
      method: "GET",
      headers: this.getRequestHeaders(),
    })
      .then(this.handleResponse)
      .then(this.handleData)
      .catch(this.handleError);
  };

  getRequestHeaders = () => ({
    'Content-Type': 'application/json',
    Authorization: localStorage.getItem('Authorization'),
  });

  handleResponse = (response) => response.json();

  handleData = (data) => {
    console.log(data.data);
    if (data.data) {
      this.setState({
        plotData: data.data,
        pieData: this.formatPieData(data.data),
        lineData: this.formatLineData(data.data),
        roseData: this.formatRoseData(data.data),
        isLoading: false
      });
    } else {
      this.setState({isLoading: false});
    }
  };

  handleError = (error) => {
    console.error("Error fetching data:", error);
    this.setState({isLoading: false});
  };

  formatPieData = (data) => data.map(item => ({
    type: item.appName,
    value: item.useTime
  }));

  // 格式化折线图数据
  formatLineData = (data) => {
    const groupedData = {};
    data.forEach(item => {
      const key = `${item.appName}-${item.stateYear}-${item.stateMonth}`; // 为每个数据项生成一个唯一的键，由应用名称、年份和月份组成
      if (!groupedData[key]) {
        groupedData[key] = { appName: item.appName, year: item.stateYear, month: item.stateMonth, useTime: 0 };
      }
      groupedData[key].useTime += parseInt(item.useTime);  // 累加同一应用在同一月的使用时间
    });
    return Object.values(groupedData);
  };

  formatRoseData = (data) => data.map(item => ({
    type: item.appName,
    people: parseInt(item.useTime),
  }));

  renderLoading = () => <div>Loading...</div>;

  renderCharts = () => {
    const {plotData, pieData, lineData, roseData} = this.state;
    const barConfig = this.getBarConfig(plotData);
    const pieConfig = this.getPieConfig(pieData);
    const lineConfig = this.getLineConfig(lineData);
    const roseConfig = this.getRoseConfig(roseData);

    return (
      <div style={{padding: '20px', overflow: 'hidden'}}>
        <Row gutter={16} style={{height: '50%'}}>
          <Col span={12} style={{height: '100%'}}>
            <Bar {...barConfig} />
          </Col>
          <Col span={12} style={{height: '100%'}}>
            <Pie {...pieConfig} />
          </Col>
        </Row>
        <Row gutter={16} style={{height: '50%', marginTop: '20px'}}>
          <Col span={12} style={{height: '100%'}}>
            <Line {...lineConfig} />
          </Col>
          <Col span={12} style={{height: '100%'}}>
            <Rose {...roseConfig} />
          </Col>
        </Row>
      </div>
    );
  };

  getBarConfig = (data) => ({
    data,
    xField: 'appName',
    yField: 'useTime',
    seriesField: 'useTime',
    legend: {
      position: 'top-left',
    },
    label: {
      style: {
        fontWeight: 'bold',
      },
    }
  });

  getPieConfig = (data) => ({
    data,
    angleField: 'value',
    colorField: 'type',
    label: {
      type: 'inner',
      content: '{percentage}',
    },
    radius: 0.8,
    legend: {
      position: 'top',
    },
  });

  getLineConfig = (data) => ({
    data,
    xField: 'month',
    yField: 'useTime',
    seriesField: 'appName',
    label: {
      style: {
        fontWeight: 'bold',
      },
    },
    interaction: {
      tooltip: {
        marker: false,
      },
    },
    style: {
      lineWidth: 2,
    },
  });

  getRoseConfig = (data) => ({
    data,
    angleField: 'people',
    colorField: 'type',
    label: {
      type: 'inner',
      content: '{percentage}',
    },
    radius: 0.8,
    legend: {
      position: 'bottom',
    },
  });

  render() {
    const {isLoading} = this.state;

    return (
      <div style={{padding: '20px'}}>
        {isLoading ? this.renderLoading() : this.renderCharts()}
      </div>
    );
  }
}

export default Demo3;

